package com.xinxin.datastructure.tree;

/**
 * @author 史鑫鑫
 * @date Created in 2019/5/30 15:05
 */
@SuppressWarnings("unchecked")
public class SegmentTree<E> {
    /**
     * 原数组
     */
    private E[] data;
    /**
     * 线段树
     */
    private E[] tree;
    private Merger<E> merger;

    /**
     * 构造函数
     *
     * @param arr    数组
     * @param merger 合并规则
     */
    public SegmentTree(E[] arr, Merger<E> merger) {
        this.merger = merger;
        data = (E[]) new Object[arr.length];
        System.arraycopy(arr, 0, data, 0, arr.length);
        tree = (E[]) new Object[4 * arr.length];
        buildSegmentTree(0, 0, data.length - 1);
    }

    /**
     * 在treeIndex的位置创建表示区间[l...r]的线段树
     *
     * @param treeIndex 当前要创建的线段树的对应的根节点的索引
     * @param l         线段对应的左端点
     * @param r         线段对应的右端点
     */
    private void buildSegmentTree(int treeIndex, int l, int r) {
        if (l == r) {
            tree[treeIndex] = data[l];
            return;
        }
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        int mid = l + (r - l) / 2;
        buildSegmentTree(leftTreeIndex, l, mid);
        buildSegmentTree(rightTreeIndex, mid + 1, r);
        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    /**
     * 返回区间内的元素个数
     *
     * @return 区间内的元素个数
     */
    public int getSize() {
        return data.length;
    }

    /**
     * 获取index索引位置的元素
     *
     * @param index 索引
     * @return 该索引位置的元素
     */
    public E get(int index) {
        if (index < 0 || index >= data.length) {
            throw new IllegalArgumentException("Index is illegal.");
        }
        return data[index];
    }

    /**
     * 返回左孩子节点的索引
     *
     * @param index 索引
     * @return 该索引左孩子的索引
     */
    private int leftChild(int index) {
        return index * 2 + 1;
    }

    /**
     * 返回右孩子节点的索引
     *
     * @param index 索引
     * @return 该索引右孩子的索引
     */
    private int rightChild(int index) {
        return index * 2 + 2;
    }

    /**
     * 返回区间[queryL, queryR]的值
     *
     * @param queryL 左边界
     * @param queryR 右边界
     * @return 合并值
     */
    public E query(int queryL, int queryR) {
        // 参数不合法
        if (queryL < 0 || queryL >= data.length ||
                queryR < 0 || queryR >= data.length ||
                queryL > queryR) {
            throw new IllegalArgumentException("Index is illegal.");
        }
        return query(0, 0, data.length - 1, queryL, queryR);

    }

    /**
     * 在以treeIndex为根的线段树中[l...r]的范围里，搜索区间[queryL, queryR]的值
     *
     * @param treeIndex 根节点索引
     * @param l         线段树左边界
     * @param r         线段树右边界
     * @param queryL    搜索区间左边界
     * @param queryR    搜索区间右边界
     * @return 搜索值
     */
    private E query(int treeIndex, int l, int r, int queryL, int queryR) {
        if (l == queryL && r == queryR) {
            return tree[treeIndex];
        }
        int mid = l + (r - l) / 2;
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        if (queryL >= mid + 1) {
            return query(rightTreeIndex, mid + 1, r, queryL, queryR);
        } else if (queryR <= mid) {
            return query(leftTreeIndex, l, mid, queryL, queryR);
        } else {
            E leftResult = query(leftTreeIndex, l, mid, queryL, mid);
            E rightResult = query(rightTreeIndex, mid + 1, r, mid + 1, queryR);
            return merger.merge(leftResult, rightResult);
        }
    }

    /**
     * 将index位置的值，更新为e
     *
     * @param index 索引
     * @param e     更新值
     */
    public void set(int index, E e) {
        if (index < 0 || index >= data.length) {
            throw new IllegalArgumentException("Index is illegal");
        }
        data[index] = e;
        set(0, 0, data.length - 1, index, e);
    }

    /**
     * 在以treeIndex为根的线段树中更新index的值为e
     *
     * @param treeIndex 根节点索引
     * @param l         左边界
     * @param r         右边界
     * @param index     更新索引值
     * @param e         更新值
     */
    private void set(int treeIndex, int l, int r, int index, E e) {
        if (l == r) {
            tree[treeIndex] = e;
            return;
        }
        int mid = l + (r - l) / 2;
        int leftTreeIndex = leftChild(treeIndex);
        int rightTreeIndex = rightChild(treeIndex);
        if (index >= mid + 1) {
            set(rightTreeIndex, mid + 1, r, index, e);
        } else {
            set(leftTreeIndex, l, mid, index, e);
        }
        tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append('[');
        for (int i = 0; i < tree.length; i++) {
            if (tree[i] != null) {
                res.append(tree[i]);
            } else {
                res.append("null");
            }
            if (i != tree.length) {
                res.append(',');
            } else {
                res.append(']');
            }
        }
        return res.toString();
    }
}
